package com.example.forum.controller;

import com.example.forum.common.AppResult;
import com.example.forum.common.ResultCode;
import com.example.forum.config.AppConfig;
import com.example.forum.model.Message;
import com.example.forum.model.User;
import com.example.forum.services.impl.MessageServiceImpl;
import com.example.forum.services.impl.UserServiceImpl;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.NonNull;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.List;

/**
 * @Description: 站内信息的controller
 * @Author Mr.Tang
 */

@Slf4j
@Api(tags = "站内信息的相关接口")
@RestController
@RequestMapping("/message")
public class MessageController {

    @Resource
    private UserServiceImpl userService;

    @Resource
    private MessageServiceImpl messageService;


    @ApiOperation("发送站内信息")
    @PostMapping("/send")
    public AppResult send(HttpServletRequest request,
                          @ApiParam("接收者id") @RequestParam("receiveUserId") @NonNull Long receiveUserId,
                          @ApiParam("信息内容") @RequestParam("content") @NonNull String content) {
        // 1. 校验当前登录的用户状态，禁言状态不能发送站内信息
        HttpSession session = request.getSession(false);
        User user = (User) session.getAttribute(AppConfig.USER_SESSION);
        if (user == null || user.getDeleteState() == 1) {
            // 用户状态异常
            return AppResult.failed("用户状态异常");
        }
        // 2. 不能给自己发送信息
        if (user.getId() == receiveUserId) {
            return AppResult.failed("不能给用户自己发送信息");
        }
        // 3. 校验接受者是否存在
        User receiver = userService.selectById(receiveUserId);
        if (receiver == null || receiver.getDeleteState() == 1) {
            return AppResult.failed("接收者状态异常");
        }
        // 4. 封装对象
        Message message = new Message();
        message.setPostUserId(user.getId());
        message.setReceiveUserId(receiveUserId);
        message.setContent(content);
        // 5. 调用Service
        messageService.create(message);
        // 6. 返回结果
        return AppResult.success("发送成功！");
    }


    @ApiOperation("获取未读信息数量")
    @GetMapping("/getUnreadCount")
    public AppResult<Integer> getUnreadCount(HttpServletRequest request) {
        // 1. 获取当前登录的用户信息
        HttpSession session = request.getSession(false);
        User user = (User) session.getAttribute(AppConfig.USER_SESSION);
        // 2. 调用service
        Integer count = messageService.selectUnreadCount(user.getId());     // 当前登录用户的id是接收者的id
        // 3. 返回结果
        return AppResult.success(count);
    }


    @ApiOperation("查询用户所有站内信")
    @GetMapping("/getAll")
    public AppResult<List<Message>> getAll(HttpServletRequest request) {
        // 1. 获取当前登录用户
        HttpSession session = request.getSession(false);
        User user = (User) session.getAttribute(AppConfig.USER_SESSION);
        // 2. 调用service
        List<Message> list = messageService.selectByReceiveUserId(user.getId());
        // 3. 返回结果
        return AppResult.success(list);
    }


    @ApiOperation("更新站内信息为已读状态")
    @PostMapping("/markRead")
    public AppResult markRead(HttpServletRequest request,
                              @ApiParam("站内信息ID") @RequestParam("id") @NonNull Long id) {
        // 1. 根据id查询站内信
        Message message = messageService.selectById(id);
        // 2. 站内信是否存在
        if (message == null || message.getDeleteState() == 1) {
            return AppResult.failed("信息不存在！");
        }
        // 3. 站内信是不是目前用户自己的
        HttpSession session = request.getSession(false);
        User user = (User) session.getAttribute(AppConfig.USER_SESSION);
        if (user.getId() != message.getReceiveUserId()) {
            return AppResult.failed("不能看别人的私信哦！");
        }
        // 4. 调用service, 把状态更新为已读(1)
        messageService.updateStateById(id, (byte) 1);
        // 5. 成功返回
        return AppResult.success();
    }


    /**
     * 回复站内信功能
     * @param repliedId 站内信id
     * @param content 内容
     * @return AppResult
     */
    @ApiOperation("回复私信")
    @PostMapping("/reply")
    public AppResult reply(HttpServletRequest request,
                           @ApiParam("要回复的站内信id") @RequestParam("repliedId") @NonNull Long repliedId,
                           @ApiParam("回复内容") @RequestParam("content") @NonNull String content) {
        // 1. 校验当前用户状态(这步不操作数据库，可以先行校验)
        HttpSession session = request.getSession(false);
        User user = (User) session.getAttribute(AppConfig.USER_SESSION);
        if (user.getState() == 1) {
            // 用户已被禁言，不能发送信息,返回错误
            return AppResult.failed(ResultCode.FAILED_USER_BANNED);
        }
        // 2. 校验要回复的站内信状态
        Message message = messageService.selectById(repliedId);
        if (message == null || message.getDeleteState() == 1) {
            // 返回错误描述
            return AppResult.failed("该信息不存在");
        }
        // 不能给自己回复
        if (user.getId() == message.getPostUserId()) {
            return AppResult.failed("不要自言自语哦~");
        }
        // 3. 构造对象
        Message replyMessage = new Message();
        replyMessage.setPostUserId(user.getId());
        replyMessage.setReceiveUserId(message.getPostUserId());
        replyMessage.setContent(content);
        // 4. 调用service
        messageService.reply(repliedId,replyMessage);
        // 5. 返回结果
        return AppResult.success();
    }




}
